package luyangzuoye.zuoye5.demos.web;

import com.rabbitmq.client.*;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class LogConsumer {
    private final static String QUEUE_NAME = "log_queue";
    private static SessionFactory sessionFactory;

    public static void main(String[] argv) throws Exception {
        // 初始化 Hibernate
        sessionFactory = new Configuration().configure().buildSessionFactory();

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        try (Connection connection = factory.newConnection(); Channel channel = connection.createChannel()) {
            channel.queueDeclare(QUEUE_NAME, false, false, false, null);
            System.out.println("Waiting for messages. To exit press CTRL+C");

            DeliverCallback deliverCallback = (consumerTag, delivery) -> {
                String message = new String(delivery.getBody(), "UTF-8");
                System.out.println("Received: " + message);

                saveLogToDatabase(message);

                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            };
            channel.basicConsume(QUEUE_NAME, false, deliverCallback, consumerTag -> { });
        }
    }

    private static void saveLogToDatabase(String message) {
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        Log log = new Log();
        log.setMessage(message);
        session.persist(log);
        session.getTransaction().commit();
        session.close();
    }
}
